<template>
  <div>
    <el-row class="addbook">
      <el-col>
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="add"
          >新建</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" v-for="item in books" :key="item.index">
        <el-card :body-style="{ padding: '0px' }" shadow="hover">
          <div class="fengmian">
            <img :src="item.avatar" class="image" />
          </div>
          <div class="zhuti">
            <h3 @click="toBook(item._id)" class="bookname">{{ item.bookname }}</h3>
            <div class="bottom">
              <!-- <template slot-scope="scope"> -->
              <el-button type="text" v-if="item.isend == 0" @click="changeIsEnd(item._id)">连载中</el-button>
              <el-button type="text" v-if="item.isend == 1" style="color:red">完结</el-button>
              <el-button @click="xiugai(item._id)">修改</el-button>
              <el-button type="danger" disabled v-if="item.state == '1'"
                >封禁中</el-button
              >
              <el-button type="success" disabled v-if="item.state == '0'"
                >正常</el-button
              >
              <el-button type="primary" disabled v-if="item.state == 2"
                >审核中</el-button
              >
              <!-- </template> -->
              <el-button type="primary" @click="deletebook(item._id)"
                >删除作品</el-button
              >
              <el-button type="primary" @click="xiezuo(item._id)"
                >去写作</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改书籍信息对话框 -->
    <el-dialog title="修改" :visible.sync="dialogVisible" width="50%">
      <div class="changePic">
        <img :src="this.thisbook.avatar" class="gaiImage" />
        <el-upload
          class="upload-demo"
          ref="upload"
          action="http://127.0.0.1:3000/api/bookAva/"
          :auto-upload="false"
          :on-remove="onRemove"
          :on-change="onChange"
          :before-upload="beforeUpload"
          :on-success = 'onSuccess'
          list-type="picture"
          name="pic"
          accept="image/jpg, image/jpeg, image/png"
        >
          <el-button size="small" type="primary" id="wei" >选取文件</el-button>
          <el-button size="small" type="success" @click="submitUpload" id="yi">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </div>
      <el-form ref="gaiFormRef" :model="thisbook" label-width="80px">
        <el-form-item label="书名" prop="bookname">
          <el-input v-model="thisbook.bookname"></el-input>
        </el-form-item>
        <el-form-item label="书籍编号" prop="id">
          <el-input v-model="thisbook._id" disabled></el-input>
        </el-form-item>
        <el-form-item label="书籍分类" prop="sort">
          <el-input v-model="thisbook.sort" disabled></el-input>
        </el-form-item>
        <el-form-item label="书籍简介" prop="explain">
          <el-input v-model="thisbook.explain"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="date">
          <el-input v-model="thisbook.date" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sub(thisbook._id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getBookList();
  },
  data() {
    return {
      books: {},
      writerid: "",
      dialogVisible: false,
      thisbook: {},
      thisBookId:''
    }
  },
  methods: {
    async getBookList() {
      const { data: res } = await this.$http.get(
        `/books/writerbook/${window.sessionStorage.getItem("writerId")}`
      );
      //console.log(res);
      if (res.status != 200) return this.$message.error("获取失败");
      this.books = res.data;
    },
    xiezuo(id) {
      let routeUrl = this.$router.resolve(`/isbook/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    async deletebook(id) {
      const { data: res } = await this.$http.delete(`books/delete/${id}`);
      if (res.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getBookList();
    },
    add() {
      this.$router.push("/addbook");
    },
    async xiugai(id) {
      this.dialogVisible = true;
      const { data: res } = await this.$http.get(`books/thisbookW/${id}`);
      this.thisbook= res.data;
      //console.log(res.data);
      this.thisBookId = res.data._id;
      // this.thisbook.bookname = res.data.bookname;
      // this.thisbook.id = res.data._id;
      // this.thisbook.sort = res.data.sort;
      // this.thisbook.explain = res.data.explain;
      // this.thisbook.date = res.data.date;
      // this.thisbook.avatar = res.data.avatar;
    },
    async sub(id) {
      //console.log(this.thisbook.bookname);
      const { data: res } = await this.$http.post(`books/changeBook/${id}`, {
        bookname: this.thisbook.bookname,
        explain: this.thisbook.explain,
      });
      if (res.status === 200) {
        this.$message.success("更改成功");
        this.dialogVisible = false;
        this.getBookList();
      }
      //console.log(id);
    },
    onChange(){
      document.getElementById("wei").style.display = 'none'
      document.getElementById("yi").style.display = 'inline'
    },
    onRemove(){
      document.getElementById("wei").style.display = 'inline'
      document.getElementById("yi").style.display = 'none'
    },
    beforeUpload(file){
      const isLt2M = file.size / 1024 < 500;
      if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return false;
        }
    },
    submitUpload() {
      this.$refs.upload.submit();
      },
    onSuccess(res){
        let url = `http://127.0.0.1:3000/uploads/book/${res.file.filename}`
        this.afterSuccess(url)
        //const{data:res} = await this.$http.post(`books/changeBookPic/${this.thisBookId}`,{url:url})
      },
    async afterSuccess(url){
      const{data:res} = await this.$http.post(`books/changeBookPic/${this.thisBookId}`,{url:url})
      console.log(res);
      if(res === 'OK'){
        this.dialogVisible = false;
        this.$refs.upload.clearFiles();
        this.getBookList();
        document.getElementById("wei").style.display = 'inline'
        document.getElementById("yi").style.display = 'none'
      }
    },
    toBook(id){
      let routeUrl = this.$router.resolve(`/tobook/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    changeIsEnd(id){
      this.$confirm(
          "将书籍改为完结状态, 此操作为不可逆操作, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            const {
              data: res,
            } = await this.$http.put(`/books/changeIsEnd/${id}`);
            if (res == "OK") {
              this.getBookList();
              this.$message({
                type: "success",
                message: "更改成功!",
              });
            } else {
              this.$message.error("更改失败");
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消更改",
            });
          });
    }
  },
};
</script>

<style lang="less" scoped>
li {
  //li取消小点
  list-style: none;
}
.gaiImage {
  //修改中封面样式
  margin: 15px;
  height: 160px;
  width: 120px;
}
.image {
  //书籍封面样式
  margin: 15px;
  height: 160px;
  width: 120px;
}
.image:hover {
  //书籍封面阴影效果
  box-shadow: 5px 5px 5px #888888;
}
.fengmian {
  //封面外部的div
  height: 176px;
  width: 20%;
  display: inline-block;
}
.zhuti {
  //书籍信息主体
  position: absolute;
  height: 176px;
  width: 80%;
  display: inline-block;
}
h3 {
  //书名样式
  margin-top: 20px;
}
.bottom {
  //书籍按钮外部div
  position: absolute;
  right: 25px;
  bottom: 5px;
}
.addbook {
  //新建书籍按钮
  margin-bottom: 7px;
}
.changePic {
  //更改书籍封面
  display: flex;
}
#yi{
  display: none;
}
//移到书名上变成小手
.bookname:hover{
  color: blue;
  cursor:pointer
}
</style>
